package com.ty;

import com.ty.utils.QuartzUtil;
import com.ty.utils.ThreadUtil;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Calendar;
import java.util.Date;

/**
 * Spring Boot启动类
 *
 * @Author Tommy
 * @Date 2022/1/26
 */
@SpringBootApplication // 默认是扫描当前包以及子包的所有类
public class BootApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(BootApplication.class, args);

        //test1();
        //test2(context);
        //test3(context);
    }

    /**
     * Calendar 测试
     */
    static void test1() {
        System.out.println("Date对象，获取星期（已过时）");
        Date d = new Date();
        System.out.println(d);
        System.out.println(d.getDay());
        System.out.println();

        System.out.println("Calendar对象，获取星期（建议使用，同时值定义也不同）");
        Calendar c = Calendar.getInstance();
        System.out.println(c.getTime());
        System.out.println(c.get(Calendar.DAY_OF_WEEK));
        System.out.println(Calendar.SUNDAY);
    }

    /**
     * 手动创建Quartz Job
     */
    static void test2(ConfigurableApplicationContext context) {
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("myJobTrigger")
                .forJob((JobDetail) context.getBean("myJobDetail"))
                .withSchedule(CronScheduleBuilder.cronSchedule("0/30 * * * * ?"))
                .withDescription("MyJob的触发器，每30秒触发一次")
                .build();
        Scheduler scheduler = context.getBean(Scheduler.class);
        try {
            scheduler.scheduleJob(trigger); // 添加Job
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        System.out.println("手动创建Quartz触发器：");
        System.out.println(trigger);
        System.out.println();

        test3(context);

        ThreadUtil.sleep(120);

        try {
            boolean result = scheduler.unscheduleJob(TriggerKey.triggerKey("myJobTrigger"));
            System.out.println("移除Job: " + result);

            ThreadUtil.sleep(60);

            scheduler.shutdown();
            System.out.println("关闭Quartz 调度器");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打印Quartz运行的Job
     */
    static void test3(ConfigurableApplicationContext context) {
        Scheduler scheduler = context.getBean(Scheduler.class);
        QuartzUtil.printInfo(scheduler);
    }
}
